package arithmetic1.map;


public class MyList<K> {
    Node<K> first;
    Node<K> last;
    int size;

    public MyList() {
    }

    //添加节点
    public boolean add(K e){
        if(first==null){
            first=new Node<K>(e,null,null);
            last = first;
            size++;
            return true;
        }
        Node<K> temp = first;
        while (temp.next != null){
            temp = temp.next;
        }
        temp.next = new Node<K>(e,temp,null);
        last = temp.next;
        size++;
        return true;
    }

    //获取指定索引的节点
    public K get(int index){
        if(index>=this.size){
            throw new RuntimeException("索引超出边界");
        }
        if(index == 0){
            return first.item;
        }
        if(index == this.size-1){
            return last.item;
        }
        int n=0;
        Node<K> temp = first;
        while (n<index){
            temp=temp.next;
            n++;
        }
        return temp.item;
    }

    //删除节点,并返回删除的节点
    public K remove(int index){
        if(index>=this.size){
            throw new RuntimeException("索引超出边界");
        }
        if(index==0){
            Node<K> node = first;
            first = first.next;
            if(first!=null){
                first.prev=null;
            }
            size--;
            return node.item;
        }
        if(index==size-1){
            Node<K> node = last;
            last = last.prev;
            last.next=null;
            size--;
            return node.item;
        }
        int n=0;
        Node<K> temp = first;
        while (n<index){
            temp = temp.next;
            n++;
        }
        Node<K> node = temp;
        node.prev.next = node.next;
        size--;
        return node.item;
    }

    //遍历节点
    public void print(){
        if (first==null){
            System.out.println("空链表");
            return;
        }
        Node<K> temp = first;
        while (temp!=null){
            System.out.print(temp.item+"-->");
            temp=temp.next;
        }
        System.out.println();
    }

    private static class Node<K>{
        K item;
        Node<K> prev;
        Node<K> next;

        Node(K item, Node<K> prev, Node<K> next) {
            this.item = item;
            this.prev = prev;
            this.next = next;
        }
    }
}
